package com.apcc4m.sfpush.handler;

import com.apcc4m.sfpush.SfpushConst;
import com.apcc4m.sfpush.listener.NettyServerListener;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class MyIdleHandler extends ChannelHandlerAdapter {

    private NettyServerListener serverListener;

    public MyIdleHandler(NettyServerListener serverListener) {
        this.serverListener = serverListener;
    }

    /**
     * 如果指定时间没有收到通知，服务器主动将连接断开，释放资源
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                System.out.println("--- Reader Idle ---");
                String deviceId = ctx.channel().attr(SfpushConst.KEY_DEVICE_ID).get();
                serverListener.removeUserChannel(deviceId);
            }
        }
    }
}
